<template>
  <div ref="chartRef" :style="{ width: '100%', height: height }"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import type { PriceHistoryItem } from '@/api/product'

interface Props {
  data: PriceHistoryItem[]
  height?: string
  currentPrice?: number
}

const props = withDefaults(defineProps<Props>(), {
  height: '400px'
})

const chartRef = ref<HTMLDivElement>()
let chartInstance: echarts.ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return

  // 销毁旧实例
  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(chartRef.value)

  // 准备数据
  const dates = props.data.map(item => item.date)
  const prices = props.data.map(item => item.price)
  const originalPrices = props.data.map(item => item.original_price || null)
  
  // 标记有促销的点
  const markPoints = props.data
    .map((item, index) => ({
      name: item.reason || '',
      xAxis: index,
      yAxis: item.price,
      value: item.reason
    }))
    .filter(item => item.value && item.value !== '正常' && item.value !== '当前价格')

  const option: echarts.EChartsOption = {
    title: {
      text: '价格走势',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'normal'
      }
    },
    tooltip: {
      trigger: 'axis',
      formatter: (params: any) => {
        const dataIndex = params[0].dataIndex
        const item = props.data[dataIndex]
        let html = `${item.date}<br/>`
        html += `<span style="color: #409EFF;">●</span> 售价: ¥${item.price.toFixed(2)}<br/>`
        if (item.original_price) {
          html += `<span style="color: #E6A23C;">●</span> 原价: ¥${item.original_price.toFixed(2)}<br/>`
        }
        if (item.reason) {
          html += `<span style="color: #F56C6C;">●</span> ${item.reason}`
        }
        return html
      }
    },
    legend: {
      data: ['售价', '原价'],
      top: 30
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: 80,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: dates,
      axisLabel: {
        rotate: 45,
        interval: Math.floor(dates.length / 10) || 0
      }
    },
    yAxis: {
      type: 'value',
      name: '价格(元)',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    series: [
      {
        name: '售价',
        type: 'line',
        data: prices,
        smooth: true,
        itemStyle: {
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.05)' }
            ]
          }
        },
        markPoint: {
          symbol: 'pin',
          symbolSize: 50,
          data: markPoints.slice(0, 5), // 只显示前5个标记点
          label: {
            fontSize: 10,
            formatter: (params: any) => {
              const value = params.value as string
              return value.length > 4 ? value.substring(0, 4) : value
            }
          }
        },
        markLine: props.currentPrice
          ? {
              silent: true,
              lineStyle: {
                color: '#67C23A',
                type: 'dashed'
              },
              data: [
                {
                  yAxis: props.currentPrice,
                  label: {
                    formatter: '当前价: ¥{c}'
                  }
                }
              ]
            }
          : undefined
      },
      {
        name: '原价',
        type: 'line',
        data: originalPrices,
        smooth: true,
        itemStyle: {
          color: '#E6A23C'
        },
        lineStyle: {
          type: 'dashed'
        }
      }
    ],
    dataZoom: [
      {
        type: 'inside',
        start: 0,
        end: 100
      },
      {
        start: 0,
        end: 100,
        height: 20,
        bottom: 10
      }
    ]
  }

  chartInstance.setOption(option)
}

// 响应式调整
const handleResize = () => {
  chartInstance?.resize()
}

onMounted(() => {
  nextTick(() => {
    initChart()
    window.addEventListener('resize', handleResize)
  })
})

watch(
  () => props.data,
  () => {
    nextTick(() => {
      initChart()
    })
  },
  { deep: true }
)

// 清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (chartInstance) {
    chartInstance.dispose()
  }
})
</script>

<style scoped>
/* 图表容器样式 */
</style>

